<template>
	<view class="image-upload">
		<view class="upload-container" @click="selectImage">
			<image 
				v-if="imageUrl" 
				:src="imageUrl" 
				class="uploaded-image"
				mode="aspectFill"
			/>
			<view v-else class="upload-placeholder">
				<text class="upload-icon">📷</text>
				<text class="upload-text">{{ placeholder }}</text>
			</view>
			
			<!-- 删除按钮 -->
			<view v-if="imageUrl && !disabled" class="delete-btn" @click.stop="deleteImage">
				<text class="delete-icon">✕</text>
			</view>
		</view>
		
		<!-- 上传进度 -->
		<view v-if="uploading" class="upload-progress">
			<text class="progress-text">上传中...</text>
		</view>
	</view>
</template>

<script>
import { getImageUrl, selectAndUploadImage } from '../utils/imageUtils.js';

export default {
	name: 'ImageUpload',
	props: {
		imageUrl: {
			type: String,
			default: ''
		},
		type: {
			type: String,
			default: 'cover'
		},
		placeholder: {
			type: String,
			default: '点击上传图片'
		},
		disabled: {
			type: Boolean,
			default: false
		}
	},
	data() {
		return {
			uploading: false
		}
	},
	methods: {
		async selectImage() {
			if (this.disabled || this.uploading) {
				return;
			}
			
			try {
				this.uploading = true;
				
				// 选择并上传图片
				const filePath = await selectAndUploadImage(this.type);
				
				// 触发父组件更新
				this.$emit('image-changed', filePath);
				
				uni.showToast({
					title: '图片上传成功',
					icon: 'success'
				});
				
			} catch (error) {
				console.error('图片上传失败:', error);
				uni.showToast({
					title: error.message || '上传失败',
					icon: 'none'
				});
			} finally {
				this.uploading = false;
			}
		},
		
		deleteImage() {
			uni.showModal({
				title: '确认删除',
				content: '确定要删除这张图片吗？',
				success: (res) => {
					if (res.confirm) {
						this.$emit('image-changed', '');
					}
				}
			});
		}
	}
}
</script>

<style scoped>
.image-upload {
	display: flex;
	flex-direction: column;
	align-items: center;
}

.upload-container {
	position: relative;
	width: 200rpx;
	height: 200rpx;
	border: 2rpx dashed #ddd;
	border-radius: 10rpx;
	overflow: hidden;
	background-color: #f9f9f9;
}

.uploaded-image {
	width: 100%;
	height: 100%;
}

.upload-placeholder {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	height: 100%;
}

.upload-icon {
	font-size: 48rpx;
	margin-bottom: 10rpx;
}

.upload-text {
	font-size: 24rpx;
	color: #999;
	text-align: center;
}

.delete-btn {
	position: absolute;
	top: 10rpx;
	right: 10rpx;
	width: 40rpx;
	height: 40rpx;
	background-color: rgba(0, 0, 0, 0.6);
	border-radius: 20rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.delete-icon {
	color: white;
	font-size: 24rpx;
}

.upload-progress {
	margin-top: 20rpx;
}

.progress-text {
	font-size: 24rpx;
	color: #666;
}
</style>
